import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { cartApi } from '../api/cart';

export function Cart() {
  const queryClient = useQueryClient();

  const { data: response } = useQuery({
    queryKey: ['cart'],
    queryFn: () => cartApi.getCart().then((res: any) => res.data),
  });

  const cart = response?.data || response;
  const items = cart?.items || [];

  const removeFromCartMutation = useMutation({
    mutationFn: (courseId: number) => cartApi.removeFromCart(courseId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['cart'] });
    },
  });

  const updateQuantityMutation = useMutation({
    mutationFn: ({ courseId, quantity }: { courseId: number; quantity: number }) =>
      cartApi.updateQuantity(courseId, quantity),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['cart'] });
    },
  });

  const total = items.reduce((sum: number, item: any) => sum + (item.course?.price || 0) * item.quantity, 0);

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold">购物车</h1>
      
      {items.length === 0 ? (
        <div className="text-center py-8">
          <p className="text-gray-500">购物车为空</p>
        </div>
      ) : (
        <>
          <div className="bg-white rounded-lg shadow">
            <div className="divide-y">
              {items.map((item: any) => (
                <div key={item.id} className="p-4 flex items-center justify-between">
                  <div className="flex items-center space-x-4">
                    <img
                      src={item.course?.thumbnail || 'https://via.placeholder.com/80x60'}
                      alt={item.course?.title}
                      className="w-20 h-16 object-cover rounded"
                    />
                    <div>
                      <h3 className="font-semibold">{item.course?.title || '未知课程'}</h3>
                      <p className="text-gray-600">¥{item.course?.price || 0}</p>
                    </div>
                  </div>
                  
                  <div className="flex items-center space-x-4">
                    <div className="flex items-center space-x-2">
                      <button
                        onClick={() => updateQuantityMutation.mutate({ 
                          courseId: item.courseId, 
                          quantity: Math.max(1, item.quantity - 1) 
                        })}
                        className="w-8 h-8 rounded border hover:bg-gray-100"
                        disabled={updateQuantityMutation.isPending}
                      >
                        -
                      </button>
                      <span className="w-8 text-center">{item.quantity}</span>
                      <button
                        onClick={() => updateQuantityMutation.mutate({ 
                          courseId: item.courseId, 
                          quantity: item.quantity + 1 
                        })}
                        className="w-8 h-8 rounded border hover:bg-gray-100"
                        disabled={updateQuantityMutation.isPending}
                      >
                        +
                      </button>
                    </div>
                    
                    <button
                      onClick={() => removeFromCartMutation.mutate(item.courseId)}
                      className="text-red-600 hover:text-red-800"
                      disabled={removeFromCartMutation.isPending}
                    >
                      删除
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </div>
          
          <div className="bg-white rounded-lg shadow p-4">
            <div className="flex justify-between items-center mb-4">
              <span className="text-lg font-semibold">总计：</span>
              <span className="text-2xl font-bold text-blue-600">¥{total}</span>
            </div>
            <button className="w-full bg-blue-600 text-white py-3 rounded-lg hover:bg-blue-700">
              去结算
            </button>
          </div>
        </>
      )}
    </div>
  );
}